using System;
using System.Web;
using System.Web.UI.WebControls;
using SubSonic;
using SurveyHost.Core.DAL;

namespace SurveyHost.Web.Admin
{
    public partial class Measures : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            StemController ctl = new StemController();
            string name = e.Keys["MeasureName"] as string;
            bool relatedExist =
                ctl.FetchByQuery(AbstractRecord<Stem>.Query()
                    .WHERE(Stem.Columns.MeasureName,
                        name))
                .Count > 0;
            if (!relatedExist) return;
            e.Cancel = true;
            SetResultText("You cannot delete measure {0} as it is associated with <a href='{1}'>questions</a>. Delete these questions or associate them with different measures first.",
                          name,
                          ResolveUrl("Questions.aspx"));
            ResultText.Visible = true;
        }

        protected void FormView1_ItemInserting(object sender, FormViewInsertEventArgs e)
        {
            e.Values["MeasureName"] = HttpUtility.HtmlEncode(e.Values["MeasureName"] as string);
        }

        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            object data = e.NewValues["Rank"];
            int rank;
            if (data == null || !int.TryParse(data as string, out rank) || rank < 1 || rank > 1000)
            {
                e.Cancel = true;
                SetResultText("Rank must be a number between 1 and 1000", null);
            }
        }

        private void SetResultText(string format, params object[] args)
        {
            ResultText.Visible = true;
            ResultText.Text = args == null ? format : string.Format(format, args);
        }

        protected void FormView1_ItemDeleted(object sender, FormViewDeletedEventArgs e)
        {
            GridView1.DataBind();
        }

        protected void FormView1_ItemInserted(object sender, FormViewInsertedEventArgs e)
        {
            GridView1.DataBind();
        }

        protected void FormView1_ItemUpdated(object sender, FormViewUpdatedEventArgs e)
        {
            GridView1.DataBind();
        }
    }
}
